import json
import time

import pymysql

route_list = []

def app(path):
    def warpper(func):
        route_list.append((path,func))
        def inner():
            pass
        return inner
    return warpper

#  @app('路径')　将路径及其对应函数引用添加到路由列表中　　而非装饰作用  flask框架添加路由的方式
@app("/gettime.html")
def get_time():
    return time.ctime()

@app("/index.html")
def index():
    """当前用户请求/index.html　执行当前函数"""
    # １　将模板文件从磁盘读取到内存中
    with open("./template/index.html","r",encoding="utf-8") as file:
        html_data = file.read()
    # 2.从数据库中读取数据
    conn = pymysql.connect(host = "192.168.199.132", port = 3306, user = "root", password = "mysql", db = "stock_db",charset = "utf8")
    cur = conn.cursor()
    cur.execute("select * from info")
    data = cur.fetchall()
    cur.close()
    conn.close()

    # 3.对模板文件进行替换《把占位符替换为用户需要的数据》
    # html_data = html_data.replace("{%content%}","this is test data")
    stock_data = ""
    for line in data:
        line_str = '''<tr>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td><input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007"></td>
           </tr>''' % line
        stock_data += line_str
    html_data = html_data.replace("{%content%}",stock_data)
    return html_data

@app('/center.html')
def center():
    """提供网页　　不提供网页数据"""
    with open("./template/center.html", encoding='utf-8') as f:
        html_data = f.read()
    html_data = html_data.replace("{%content%}","")
    return html_data

@app("/center_data.html")
def center_data():
    # 1. 从数据库中读取数据
    sql = "select i.code,i.short,i.chg,i.turnover, i.price,i.highs, focus.note_info from info i inner join focus on i.id = focus.info_id"
    conn = pymysql.connect(host="192.168.199.132", port=3306, user="root", password="mysql", db="stock_db",
                           charset="utf8")
    cur = conn.cursor()
    cur.execute(sql)
    data = cur.fetchall()
    cur.close()
    conn.close()
    # 2. 将用户转化为用户需要的JSON格式
    data_list = list()
    for row in data:
        center_dict = dict()
        center_dict["code"] = row[0]
        center_dict["short"] = row[1]
        center_dict["chg"] = row[2]
        center_dict["turnover"] = row[3]
        center_dict["price"] = str(row[4])
        center_dict["highs"] = str(row[5])
        center_dict["note_info"] = row[6]
        data_list.append(center_dict)
    # 3 将python到处为JSON字符串
    json_data = json.dumps(data_list,ensure_ascii=False)
    return json_data
# 路由列表    路径　　　函数引用
# 增加了框架可维护性　　　app的代码不用做任何修改可以直接添加功能　　django框架添加路由方式
# route_list = [("/index.html",index),("/gettime.html", get_time)]


def app(env):
    path_info = env['PATH_INFO']
    print("框架收到动态资源请求 %s" % path_info)
    for path, func in route_list:
        if path_info == path:
            return '200OK', [("server", "APP1.1")],func()
    else:
        return '404OK', [("server", "APP1.1")],'hello world'
